<?php
namespace app\index\controller;

use app\index\model\Orders;
use app\index\model\Shop;
use app\index\model\Userapp;
use think\Db;
use think\Session;
use think\View;

class Index extends Base
{
    /**
     * 首页框架
     * @return \think\response\View
     */
    public function index()
    {
//        View::share("hello","world");//模板赋值
		return view();
    }

    /**
     * 营业统计
     */
    public function statistics(){
        $totalpage=0;
        $shopmodel=new Shop();
        $ttgshop=$shopmodel->where(["id"=>Session::get("shopid")])->find();
        if(empty($ttgshop['ttgshopno'])){
            die("您的账号尚未绑定TTG门店编号");
        }
        //获取淘淘谷门店的具体信息
        $ttginfo=Db::name("ttg")->where("id",$ttgshop['ttgid'])->find();
        if(empty($ttginfo["ttgid"])||empty($ttginfo["ttgkey"])){
            die("淘淘谷配置错误!");
        }
        $tlinksdk=new \Mylinx($ttginfo["ttgid"], $ttginfo["ttgkey"],$ttgshop['ttgid']);
        $data['page'] = 1; //初始页数
        $data['shop_no'] =$ttgshop['ttgshopno'];//门店编号
        $data['pagesize']=100; //每页数字
        $data['sdate']=date("Y-m-d");
        $data['edate']=date("Y-m-d");
        $orderlist=[];
        do{
            $result = $tlinksdk->API('order', $data);
            if($result["data"]["pages"]["totalpage"]==0){
                break;
            }
            $data['page']++;
            if($result["errcode"]==1){
                die($result["msg"]);
            }else{
                $orderlist=array_merge($orderlist,$result["data"]["list"]);
                $totalpage=$result["data"]["pages"]["totalpage"];
            }
        }while( $data['page']<=$totalpage);
//        dump($orderlist);exit();
        View::share("res",self::calorder($orderlist));
        return view();
    }

    /**
     * POS订单交易记录
     */
    public function orderlist(){

        $shopmodel=new Shop();
        $ttgshop=$shopmodel->where(["id"=>Session::get("shopid")])->find();
        $totalpage=0;
        if(empty($ttgshop['ttgshopno'])){
            die("您的账号尚未绑定TTG门店编号");
        }
        //获取淘淘谷门店的具体信息
        $ttginfo=Db::name("ttg")->where("id",$ttgshop['ttgid'])->find();
        if(empty($ttginfo["ttgid"])||empty($ttginfo["ttgkey"])){
            die("淘淘谷配置错误!");
        }
        $tlinksdk=new \Mylinx($ttginfo["ttgid"], $ttginfo["ttgkey"],$ttgshop['ttgid']);
        $data['page'] = 1; //初始页数
        $data['shop_no'] =$ttgshop['ttgshopno'];//门店编号
        $data['pagesize']=20; //每页数字
        if(request()->get("ordstatus")!=null)$data['status']=request()->get("ordstatus");
        if(request()->get("sdate")!=null)$data['sdate']=request()->get("sdate");
        if(request()->get("edate")!=null)$data['edate']=request()->get("edate");
        if(request()->get("ordersn")!=null)$data['ord_no']=request()->get("ordersn");
        if(request()->get("page")!=null)$data['page']=request()->get("page");
//        $result = $tlinksdk->API('shop/openid', ["shop_no"=>$ttgshop['ttgshopno']]);
        $result = $tlinksdk->API('order', $data);
        if($result["errcode"]==1){
            die($result["msg"]);
        }else{
            if($result["data"]["pages"]["totalpage"]==0){
                $res=[];
            }else{
                $totalpage=$result["data"]["pages"]["totalpage"];
                $res=$result["data"]["list"];
            }
        }
        View::share("totalpage",$totalpage);
        View::share("res",$res);
        return view();
    }

    /**
     * 计算订单
     */
    private static function calorder($orderlist){
        $totaltransaction=0;
        $transactionnumber=0;
        if(empty($orderlist)){
            return [
                "totaltransaction"=>$totaltransaction,
                "transactionnumber"=>$transactionnumber,
                "takeincome"=>0,
                "groupincome"=>0
            ];
        }else{
            foreach ($orderlist as $k=>$v){
                if(($v["ord_type"]=="1")&&($v["ord_status"]=="1")){
                    $transactionnumber++;
                    $totaltransaction+=intval($v["ord_trade_amount"]);
                }else{
                    continue;
                }
            }
            return [
                "totaltransaction"=>$totaltransaction,
                "transactionnumber"=>$transactionnumber,
                "takeincome"=>0,
                "groupincome"=>0
            ];
        }
    }

    public function exportdata(){
        set_time_limit(0);//防止超时
        $tlinksdk=new \tlinxsdk();
        $totalpage=0;
        $shopmodel=new Shop();
        $ttgshopno=$shopmodel->where(["id"=>Session::get("shopid")])->column("ttgshopno");
        if(empty($ttgshopno[0])){
            die("您的账号尚未绑定TTG门店编号");
        }
        $data['page'] = 1; //初始页数
        $data['shop_no'] =$ttgshopno[0];//门店编号
        $data['pagesize']=100; //每页数字
        if(request()->get("ordstatus")!=null)$data['status']=request()->get("ordstatus");
        if(request()->get("sdate")!=null)$data['sdate']=request()->get("sdate");
        if(request()->get("edate")!=null)$data['edate']=request()->get("edate");
        if(request()->get("ordersn")!=null)$data['ord_no']=request()->get("ordersn");
        $orderlist=[];
        do{
            $result = $tlinksdk->API('order', $data);
            if($result["data"]["pages"]["totalpage"]==0){
                break;
            }
            $data['page']++;
            if($result["errcode"]==1){
                die($result["msg"]);
            }else{
                $orderlist=array_merge($orderlist,$result["data"]["list"]);
                $totalpage=$result["data"]["pages"]["totalpage"];
            }
        }while( $data['page']<=$totalpage);

        $cellname=[
            array('ord_no', '订单号'),
            array('ord_add_time', '下单时间'),
            array('ord_trade_pay_time', '交易时间'),
            array('mct_name', '商户名称'),
            array('shop_name', '门店名称'),
            array('ord_status', "交易状态"),
            array('original_ord_no', '平台交易号'),
            array('ord_type', '交易类型'),
            array('pmt_name', '付款方式'),
            array('ord_original_amount', '原始金额'),
            array('ord_discount_amount', '优惠金额'),
            array('ord_trade_amount', '实际金额'),
            array('ord_fee', '手续费'),
            array('ord_org_fee', '平台分润'),
            array('ord_agent_fee', '机构分润'),
            array('org_name','机构'),
            array('tml_no','机器编号'),
//            array('payinfo','付款信息'),
            array('credit_card','信用卡'),
            array('original_ord_no','原始订单号'),
//            array('third_ord_no','第三方交易号')
        ];

        $orderlist=array_map(function($v){
            return [
                'ord_add_time'=>$v["ord_add_time"],
                'ord_no'=> " ".$v['ord_no'],
                'original_ord_no'=>" ".$v['original_ord_no'],
                'shop_name'=>$v['shop_name'],
                'ord_trade_pay_time'=> $v['ord_trade_pay_time'],
                'pmt_name'=>$v['pmt_name'],
                'ord_original_amount'=> number_format($v['ord_original_amount']/100,2,".",""),
                'ord_discount_amount'=>number_format($v['ord_discount_amount']/100,2,".",""),
                'ord_trade_amount'=> number_format($v['ord_trade_amount']/100,2,".",""),
                'ord_type'=> getordtype($v['ord_type']),
                'ord_status'=>getordstatus($v['ord_status']),
                'mct_name'=>$v["mct_name"],
                'ord_fee'=> number_format($v['ord_fee']/100,2,".",""),
                'ord_org_fee'=> number_format($v['ord_org_fee']/100,2,".",""),
                'ord_agent_fee'=> number_format($v['ord_agent_fee']/100,2,".",""),
                'org_name'=>$v["org_name"],
                'tml_no'=>$v["tml_no"],
//                'payinfo'=>$v["payinfo"],
                'credit_card'=>$v["credit_card"],
                'original_ord_no'=>" ".$v["original_ord_no"]
            ];
        },$orderlist);
        if(empty($orderlist)){die("数据为空,无法导出!");}
        $xlsTitle = iconv('utf-8', 'gb2312', "POS交易导出表".date("Y-m-d H:i:s")); //文件名称
        $fileName = "订单导出表" . date('_YmdHis'); //or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($cellname);
        $dataNum = count($orderlist);
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        for($i = 0;$i < $cellNum; $i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $cellname[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i = 0;$i < $dataNum; $i++){
            for($j = 0; $j < $cellNum; $j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 2), $orderlist[$i][$cellname[$j][0]]);
            }
        }
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls"); //attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }

    /**
     * 空操作
     * @return string
     */
    public function _empty(){
        return "您输入的网址有误!";
    }

    /**
     * 所有应用
     */
    public function allapp(){
        $res=model("applist")->where("y_applist.status",1)->join("y_appdetail","y_appdetail.pid=y_applist.id","left")->field("y_appdetail.logourl,y_applist.*")->select();
        View::share("res",$res);
        return \view();
    }

    /**
     * 所有应用
     */
    public function appdetail(){
        if(request()->isAjax()){
            $userapp=new Userapp();
            $res=$userapp->buyapp(Session::get("managerid"));
            if($res){
                return json(["status"=>1,"msg"=>"购买成功"]);
            }else{
                return json(["status"=>0,"msg"=>"购买失败"]);
            }
        }else{
            //查询该应用的详情
            $res=model("applist")->where("y_applist.id",request()->param("id"))->join("y_appdetail","y_appdetail.pid=y_applist.id","left")->field("y_appdetail.logourl,y_applist.*")->find();
            $useage=model("userapp")->where("shopid",Session::get("shopid"))->where("appid",request()->param("id"))->find();
            View::share("res",$res);
            View::share("useage",$useage);
            //查询该用户的购买情况
            return \view();
        }
    }

    /**
     * 我的应用
     * @datetime 2017年4月22日 14:49:46
     */
    public function myapp(){
        $res=model("userapp")->where("shopid",Session::get("shopid"))->join("y_applist","y_applist.id=y_userapp.appid","left")->join("y_appdetail","y_appdetail.pid=y_applist.id","left")->field("y_appdetail.logourl,y_applist.*,y_userapp.endtime")->select();
        View::share("res",$res);
        return \view();
    }

    /**
     * 我的外卖订单统计
     * @datetime 2017年4月22日 15:22:28
     */
    public function mytakeout(){
        if(request()->isAjax()){
            //接受POST条件,返回相关数据
            $res=Orders::searchorder(request()->post());
            return json(["status"=>1,"data"=>$res]);
        }else{
            return \view();
        }
    }

    /**
     * 下载外卖订单
     */
    public function downtakeout(){
        if(request()->isGet()){
            Orders::downorder(request()->get());
        }
    }


}
